﻿using AdminBase.Common.Attributes;
using AdminBase.Common.Helpers;
using AdminBase.Model;
using AdminBase.Model.Common;
using AdminBase.Model.Entitys;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Reflection;

namespace AdminBase.webapi.Controllers
{
    /// <summary>
    /// 工具控制器
    /// </summary>
    [Route("[controller]")]
    [ApiController]
    [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
    [TypeFilter(typeof(AsyncExceptionFilterAttribute))]
    public class ToolController : ControllerBase
    {
        /// <summary>
        /// sqlsugar
        /// </summary>
        public ISqlSugarClient _db;
        private readonly RedisHelper _redis;

        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="db"></param>
        public ToolController(ISqlSugarClient db, RedisHelper redis)
        {
            _db = db;
            _redis = redis;
        }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("initdb")]
        public string InitDateBase()
        {
            string res = "OK";

            //如果不存在则创建数据库
            _db.DbMaintenance.CreateDatabase();
            // 模型地址
            string nspace = "AdminBase.Model.Entitys";
            //通过反射读取我们想要的类
            Type[] ass = Assembly.LoadFrom(AppContext.BaseDirectory + "AdminBase.Model.dll")
                .GetTypes().Where(p => p.Namespace == nspace).ToArray();

            _db.CodeFirst.SetStringDefaultLength(200).InitTables(ass);

            //初始化管理员和菜单
            Users user = new Users()
            {
                UserName = "admin",
                IsSuperUser = true
            };
            long userId = _db.Insertable(user).ExecuteReturnBigIdentity();

            return res;
        }

        /// <summary>
        /// 测试
        /// </summary>
        /// <returns></returns>
        [Route("test")]
        [HttpPost]
        [Idempotent]
        public ApiResult Test()
        {
            return ResultHelper.Success(RedisHelper.StringIncrement("test"));
        }
        /// <summary>
        /// 测试
        /// </summary>
        /// <returns></returns>
        [Route("test")]
        [HttpGet]
        [Idempotent]
        public ApiResult GetTest()
        {
            return ResultHelper.Success(RedisHelper.GetValue("test"));
        }
    }
}
